<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert title="注意：只允许为第三方分类设置相关参数"
                type="warning"
                :closable="false"
                show-icon>
      </el-alert>
      <el-row>
        <el-col>
          <span>
            选择商品分类：
          </span>
          <span>
            <el-cascader v-model="selectCategoryarray"
                         :options="categoryList"
                         :props="categoryProps"
                         size="medium"
                         clearable
                         @change="changeCategory"></el-cascader>
          </span>
        </el-col>
        <el-col>
        </el-col>
      </el-row>

      <!-- tab标签页 -->
      <el-tabs v-model="activeTab"
               @tab-click="selectTab">
        <el-tab-pane label="动态参数"
                     name="many">
          <!-- 添加动态参数的按钮 -->
          <el-button type="primary"
                     @click="addAttribute"
                     :disabled="selectCategoryarray.length !== 3">添加参数</el-button>

          <el-table :data="manyTabData"
                    style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 已存在的属性值 -->
                <el-tag v-for="(item,i) in scope.row.attr_vals"
                        closable
                        @close="handleClose(i,scope.row)"
                        :key="i">
                  {{item}}
                </el-tag>
                <!-- 控制添加和输入框的标签 -->
                <el-input class="input-new-tag"
                          v-if="scope.row.inputVisible"
                          v-model="scope.row.inputValue"
                          ref="saveTagInput"
                          size="small"
                          @keyup.enter.native="handleInputConfirm(scope.row)"
                          @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else
                           class="button-new-tag"
                           size="small"
                           @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column label="#"
                             type="index">
            </el-table-column>
            <el-table-column prop="attr_name"
                             label="属性名">
            </el-table-column>
            <el-table-column prop="attr_write"
                             label="属性类型">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary"
                           @click="showEditDialog(scope.row.attr_id)"
                           icon="el-icon-edit">编辑</el-button>
                <el-button type="danger"
                           @click="removeAttr(scope.row.attr_id)"
                           icon="el-icon-delete">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性"
                     name="only">
          <el-button type="primary"
                     @click="addAttribute"
                     :disabled="selectCategoryarray.length !== 3">添加属性</el-button>
          <el-table :data="onlyTabData"
                    style="width: 100%">
            <el-table-column type="expand">
            </el-table-column>
            <el-table-column label="#"
                             type="index">
            </el-table-column>
            <el-table-column prop="attr_name"
                             label="属性名">
            </el-table-column>
            <el-table-column prop="attr_write"
                             label="属性类型">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary"
                           @click="showEditDialog(scope.row.attr_id)"
                           icon="el-icon-edit">编辑</el-button>
                <el-button type="danger"
                           @click="removeAttr(scope.row.attr_id)"
                           icon="el-icon-delete">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数或者属性的对话框 -->
    <el-dialog :title="'添加'+getOperateType()"
               :visible.sync="addAttributeDialogVisible"
               width="100%"
               @close="closeAddAttributeDialog">

      <el-form :model="addAttributeForm"
               :rules="attributeRules"
               ref="addAttributeFormRef">
        <el-form-item :label="getOperateType()"
                      prop="attr_name">
          <el-input v-model="addAttributeForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer"
            class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="submitAttribute">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改属性 -->
    <el-dialog :title="'修改'+getOperateType()"
               :visible.sync="editAttributeDialogVisible"
               width="100%"
               @close="closeAddAttributeDialog">

      <el-form :model="editAttributeForm"
               :rules="attributeRules"
               ref="editAttributeForm">
        <el-form-item :label="getOperateType()"
                      prop="attr_name">
          <el-input v-model="editAttributeForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer"
            class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="updateAttr">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 分类列表
      categoryList: [],
      // 级联选择框的配置属性
      categoryProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name'
      },
      // 级联选择框选择的双向绑定的数组
      selectCategoryarray: [],
      activeTab: 'many',
      // 不同的数据源  动态参数数据源
      manyTabData: [],
      // 静态属性数据源
      onlyTabData: [],
      // 控制添加属性对话框的显示和隐藏
      addAttributeDialogVisible: false,
      // 添加参数属性的表单对象
      addAttributeForm: {},
      // 添加属性时候的校验规则
      attributeRules: {
        attr_name: [
          { required: true, message: '请输入属性', trigger: 'blur' },
          { min: 1, max: 20, message: '请输入1-20个字符', trigger: 'blur' }
        ]
      },
      editAttributeDialogVisible: false,
      // 修改参数属性的表单对象
      editAttributeForm: {}
    }
  },
  created () {
    this.getCategoryList()
  },
  methods: {
    async getCategoryList () {
      const { data: res } = await this.$http.get('categories')
      this.categoryList = res.data
    },
    async changeCategory () {
      if (this.selectCategoryarray.length !== 3) {
        this.$message.warn('请选择三级分类')
        this.selectCategoryarray = []
      }
      this.getAttributeAndParams()
    },
    // tab被选中时触发
    selectTab () {
      this.getAttributeAndParams()
    },
    // 获取动态参数和静态属性的函数
    async getAttributeAndParams () {
      // 发送请求得到这个第三级分类的参数
      const { data: res } = await this.$http.get(
        `categories/${
          this.selectCategoryarray[this.selectCategoryarray.length - 1]
        }/attributes`,
        {
          params: { sel: this.activeTab }
        }
      )
      // 将属性值分割并放到数组里面
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeTab === 'many') {
        this.manyTabData = res.data
      } else if (this.activeTab === 'only') {
        this.onlyTabData = res.data
      }
      console.log(this.manyTabData)
    },
    // 获取添加类型，
    getOperateType () {
      if (this.activeTab === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    },
    // 关闭对话框触发的事件
    closeAddAttributeDialog () {
      this.addAttributeForm = {}
    },
    addAttribute () {
      this.addAttributeDialogVisible = true
    },
    submitAttribute () {
      this.$refs.addAttributeFormRef.validate(async vali => {
        if (!vali) {
          return
        }
        const { data: res } = await this.$http.post(
          `categories/${
            this.selectCategoryarray[this.selectCategoryarray.length - 1]
          }/attributes`,
          {
            attr_name: this.addAttributeForm.attr_name,
            attr_sel: this.activeTab
          }
        )
        if (res.meta.status !== 201) {
          return this.$message.error('添加参数失败')
        }
        this.$message.success('添加成功')
        this.addAttributeDialogVisible = false
        this.addAttributeForm = {}
        this.getAttributeAndParams()
      })
    },
    async showEditDialog (val) {
      console.log(val)
      const { data: res } = await this.$http.get(
        `categories/${
          this.selectCategoryarray[this.selectCategoryarray.length - 1]
        }/attributes/${val}`
      )
      this.editAttributeForm = res.data
      this.editAttributeDialogVisible = true
    },
    updateAttr () {
      this.$refs.editAttributeForm.validate(async vali => {
        if (!vali) {
          return
        }
        const { data: res } = await this.$http.put(
          `categories/${
            this.selectCategoryarray[this.selectCategoryarray.length - 1]
          }/attributes/${this.editAttributeForm.attr_id}`,
          {
            attr_name: this.editAttributeForm.attr_name,
            attr_sel: this.activeTab
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('更新失败')
        }
        this.$message.success('更新成功')
        this.editAttributeForm = {}
        this.editAttributeDialogVisible = false
        this.getAttributeAndParams()
      })
    },
    async removeAttr (val) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(
        `categories/${
          this.selectCategoryarray[this.selectCategoryarray.length - 1]
        }/attributes/${val}`
      )
      if (res.meta.status !== 200) {
        this.$message.error('删除失败')
      }
      this.$message.success('删除成功')
      this.getAttributeAndParams()
    },
    // 文本框按下回车或者失去焦点都会触发该事件
    async handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      // 如果没有return，证明输入真实内容，需要请求服务端
      row.attr_vals.push(row.inputValue)
      row.inputValue = ''
      row.inputVisible = false
      console.log(row.attr_vals)
      this.saveAttr(row)
      this.$message.success('添加成功')
    },
    // 控制文本框显示或者隐藏
    showInput (row) {
      row.inputVisible = !row.inputVisible
      // $nextTick作用：就是当页面上元素被重新渲染之后，才回指定回调函数中的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleClose (i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttr(row)
    },
    async saveAttr (row) {
      const { data: res } = await this.$http.put(
        `categories/${
          this.selectCategoryarray[this.selectCategoryarray.length - 1]
        }/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        }
      )
    }
  }
}
</script>

<style>
.input-new-tag {
  width: 120px;
}
</style>
